"use strict";

import { parseLyricTag} from "./lyricCommon"
/**
 * 解析LRC歌词
 * @param lyricText 歌词文本
 */
export function parse(lyricText) {
    //结果
    const result = { type: "REG", content: [] };
    //逐行处理
    lyricText.split(/\r?\n/).forEach(line => {
        line = line.trim();
        //匹配歌词时间
        const startTimes = [];
        while (true) {
            //匹配歌词时间
            const match = line.match(/^\[(\d+):(\d+)(\.(\d+))?\]/);
            if (match) {
                //取得时间
                const min = parseInt(match[1].replace(/^0+/, '0'));
                const sec = parseInt(match[2].replace(/^0+/, '0'));
                let sec100 = match[4] ? parseInt(match[4].replace(/^0+/, '')) : 0;
                if (isNaN(min) || isNaN(sec))
                {
                    return;
                }
                if (isNaN(sec100))
                    sec100 = 0;
                const startTime = (min * 60 * 1000) + (sec * 1000) + (sec100 * 10);
                //保存时间继续处理
                if (!startTimes.includes(startTime))
                    startTimes.push(startTime);
                line = line.substring(match[0].length).trim();
            }
            //没有匹配到
            else{
                break;
            }

        }
        if (!line)
            return;
        //如果匹配到时间
        if (startTimes.length)
            result.content.push(...startTimes.map(start => ({ start, content: line })));
        //没有匹配到歌词
        else
            parseLyricTag(result, line);
    });
    //排序一下吧
    result.content = result.content.sort((a, b) => a.start - b.start);
    return result;
}

/**
 * 歌词转换为文本
 * @param lyric 歌词
 */
export function stringify(lyric) {
    const buffer = [];
    if (lyric.ti)
        buffer.push(`[ti:${lyric.ti}]`);
    if (lyric.ar)
        buffer.push(`[ar:${lyric.ar}]`);
    if (lyric.al)
        buffer.push(`[al:${lyric.al}]`);
    if (lyric.by)
        buffer.push(`[by:${lyric.by}]`);
    if (lyric.offset)
        buffer.push(`[offset:${lyric.offset}]`);
    lyric.content.forEach(line => {
        const min = parseInt(line.start / 1000 / 60).toString().padStart(2, '0');
        const sec = parseInt((line.start / 1000) % 60).toString().padStart(2, '0');
        const sec100 = parseInt((line.start % 1000) / 10).toString().padStart(2, '0');
        //文本处理
        const text = (typeof line.content == 'string') ? line.content : line.content.map(s => s.content).join('');
        buffer.push(`[${min}:${sec}.${sec100}]${text}`);
    });
    return buffer.join('\n');
}

